import React from 'react';
import {Image, Linking, Modal, StyleSheet, Text} from 'react-native';
import BasePage from './BasePage';
import ViewUtils from '../utils/ViewUtils';
import NavigationBar from './common/NavigationBar';
import {commonStyles} from '../configs/commonStyle';
import ImageViewer from 'react-native-image-zoom-viewer';
import AutoHeightWebView from 'react-native-autoheight-webview';
import {inject, observer} from 'mobx-react';
import {View} from 'react-native-ui-lib';

/**
 * 加载html标签内容
 */
@inject("userStore")
@observer
export default class Html extends BasePage {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            title: this.params.title || '',
            subTitle: this.params.subTitle || '',
            htmlContent: this.params.htmlContent,
            time: this.params.time,
            isImageShow: false,
            images: [],
            selectIndex: 0,
        }
    }


    onMessage = (event) => {
        try {
            Log('js回调', event.nativeEvent.data)
            if (!event.nativeEvent.data.includes('this.setHeight')) {
                const action = JSON.parse(event.nativeEvent.data);
                Log(action);
                if (action.type == 'a' && action.url) {
                    Linking.openURL(`${action.url}`).catch(Log)
                }
                else if (action.type == 'img') {
                    var pos = 0;
                    for (let i = 0; i < action.images.length; i++) {
                        if (action.images[i].url == action.url) {
                            break;
                        }
                        pos++;
                    }
                    this.setState({isImageShow: true, images: action.images, selectIndex: pos});
                }
            }

        } catch (error) {
            console.log(error)
        }
    }

    render() {
        const {title, htmlContent, time} = this.state;
        Log('公告详情', htmlContent);
        const fun = `
         setTimeout(() => {
                             var objs =document.getElementById("downfile");
                             if(objs){
                                 objs.onclick=function(e){
                                        e.preventDefault();
                                        if(window.ReactNativeWebView.postMessage) {
                                            window.ReactNativeWebView.postMessage(JSON.stringify({
                                                    type: 'a',
                                                    url: this.href
                                              }));
                                        }
                                    }
                                }
                               
                               var lives =document.getElementById("openLive");
                                 if(lives){
                                     lives.onclick=function(e){
                                            e.preventDefault();
                                            if(window.ReactNativeWebView.postMessage) {
                                                window.ReactNativeWebView.postMessage(JSON.stringify({
                                                        type: 'live',
                                                        url: this.href
                                                  }));
                                            }
                                        }
                                    }
                                
                                var aNodes = document.getElementsByTagName("img");
                                
                                if(aNodes){
                                    var images = [];
                                    for(var j=0;j<aNodes.length;j++){
                                        var object = aNodes[j];
                                        images.push({url:object.src});
                                    }
                                    for(var i=0;i<aNodes.length;i++){
                                        aNodes[i].onclick=function(){
                                            if(window.ReactNativeWebView.postMessage) {
                                            
                                                window.ReactNativeWebView.postMessage(JSON.stringify({
                                                        type: 'img',
                                                        url: this.src,
                                                        images: images
                                                  }));
                                            }
                                        }
                                    }
                                }
                                
                             },500);
        
        `;
        return (
            <View useSafeArea style={commonStyles.container}>
                <View style={styles.container}>
                    <NavigationBar
                        leftButton={ViewUtils.getLeftButton(() => {
                            this._onBackPress()
                        })}
                        title={'消息详情'}/>
                    <View style={{paddingHorizontal: 15, marginBottom: 10, marginTop: 20}}>
                        <Text style={commonStyles.text_black_20}>{title}</Text>
                    </View>
                    <View style={{paddingHorizontal: 15, marginBottom: 20}}>
                        <Text style={commonStyles.text_gray_14}>时间： {time}</Text>
                    </View>

                    <View style={{flex: 1, paddingHorizontal: 15}}>
                        <AutoHeightWebView
                            style={{backgroundColor: '#fff', width: '100%',opacity: 0.99}}
                            source={{html: htmlContent, baseUrl: ''}}
                            scalesPageToFit={true}
                            customScript={fun}
                            customStyle={`
                                          * {
                                          }
                                          h1 {color: #333333;}
                                          p {
                                            font-size: 16px;
                                            color:#666666;
                                          }
                                        `}
                            javaScriptEnabled={true}
                            onMessage={this.onMessage}
                            mixedContentMode={'compatibility'}
                            viewportContent={'width=device-width, user-scalable=no'}
                        />
                    </View>


                </View>
                {
                    this.state.isImageShow ?
                        <Modal visible={true} transparent={true}
                               onRequestClose={() => {
                                   this.setState({
                                       isImageShow: false,
                                   });
                               }}>
                            <ImageViewer imageUrls={this.state.images}
                                         onClick={() => {
                                             this.setState({
                                                 isImageShow: false,
                                             });
                                         }}
                                         renderImage={r => <Image
                                             style={r.style}
                                             source={r.source}
                                             resize={'resize'}
                                         />}
                                         index={this.state.selectIndex}
                                         saveToLocalByLongPress={false}/>
                        </Modal>
                        : null
                }
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});
